import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../networking/http_manager.dart';
import '../widget/my_dialog.dart';
export '../widget/my_dialog.dart';


/*  使用示例：

    class LoginController extends BaseController {
      ...
      ...
      ...
      如果是有分页的页码
      requestDataList() async {
        final param = { };
        final result = await ClientRequest.getClients(param);
        super.modelAnalyzingWith(result, models, model, fromJson: ClientModel.fromJson);
      }

      如果分页没有页码，而是 lastId
      requestDataList({String lastID = ""}) async {
        if (lastID.isEmpty || lastID == "0") { models.clear(); }
        final result = await requestMessageListData(notificationId: lastID);
        final response = <MyMessageModel>[].obs;
        super.modelAnalyzingWith(result, response, null, fromJson: MyMessageModel.fromJson);
        models.addAll(response);
      }
    }

 */


class BaseController extends GetxController {
  // 根据服务器返回结果码，用来控制界面的变化
  final state = ResultCode.loading.obs;
  // 下拉刷新上拉加载的控制器
  final refreshCtrl = EasyRefreshController(controlFinishLoad: true, controlFinishRefresh: true);

  // 分页模型
  PageModel page = PageModel();

  // 结束编辑，防止键盘遮挡
  endEditing() => FocusScope.of(Get.context!).requestFocus(FocusNode());
  closeKeyboard() => endEditing();

  // 下拉刷新的函数
  Future<void> onRefresh() async {
    refreshCtrl.finishRefresh();
    refreshCtrl.resetFooter();
  }

  // 上拉加载的函数
  Future<void> onLoad() async {
    if (page.nextPagination == -1 || state.value == ResultCode.no_more_data) {
      refreshCtrl.finishLoad(IndicatorResult.noMore);
    }else {
      refreshCtrl.finishLoad(IndicatorResult.success);
    }
  }

  // 一个通用的 analyzing 函数，使用泛型和函数参数
  Future<void> modelAnalyzingWith<T>(ResponseAnalyzed result, var listModel, var model, {T Function(Map<String, dynamic>)? fromJson}) async {
    if (result.success && result.data != null) {
      if (result.data is Map && result.data.isNotEmpty) {
        // 如果是一个分页的字典对象
        if (result.data.containsKey("pagination")) {
          page = PageModel.fromJson(result.data);
          if (page.dataList != null && page.dataList is List && page.dataList!.isNotEmpty) {
            if (fromJson != null) {
              final data = (page.dataList as List).map((i) => fromJson(i)).toList();
              if (page.pagination != null && page.pagination! <= 1) {
                listModel.clear();
              }
              listModel.addAll(data);
            }else {
              debugPrint("resultAnalyzingModel 分页的字典对象: fromJson = null");
            }
          }
          // 服务器有时候不按标准执行，在不是上拉加载的时候返回了 20003
          if (page.dataList!.isEmpty || (page.pagination! <= 0 && result.code == ResultCode.no_more_data)) {
            listModel.clear();
            state.value = ResultCode.empty_data;
            return;
          }
        }else {
          // 是一个单纯的字典对象
          if (fromJson != null) {
            final data = fromJson(result.data);
            if (model is Rx) {
              model.value = data;
            }else {
              model = data;
              if (kDebugMode) showMessage("model != Rxs");
              debugPrint("resultAnalyzingModel 一个单纯的字典对象: model != Rx");
            }
          }else {
            debugPrint("resultAnalyzingModel 一个单纯的字典对象: fromJson = null");
          }
        }
      }else if (result.data is List && result.data.isNotEmpty) {
        // 一个数组对象
        if (fromJson != null) {
          final data = (result.data as List).map((i) => fromJson(i)).toList();
          if (listModel is RxList) {
            listModel.value = data;
          }else {
            listModel.clear();
            listModel.addAll(data);
          }
        }else {
          debugPrint("resultAnalyzingModel 一个单纯数组对象: fromJson = null");
        }
      }
    }
    state.value = result.code!;
  }
}


class BaseModel {
  String? code, message;
  BaseModel({this.code, this.message});
  BaseModel.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    message = json['message'];
  }
}

// 页码模型
class PageModel {
  dynamic dataList;
  num? dataCount, pagination, nextPagination, paginationCount;
  PageModel({this.dataCount=20,this.pagination=0,this.nextPagination=0,this.paginationCount=20,this.dataList});
  PageModel.fromJson(Map<String, dynamic> json) {
    dataCount = json['dataCount'];
    pagination = json['pagination'];
    nextPagination = json['nextPagination'];
    paginationCount = json['paginationCount'];
    dataList = json['dataList'];
  }
}